/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities1.Event;
import entities1.InvitationRequest;
import entities1.Notification;
import java.util.List;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.joda.time.DateTime;



/**
 *
 * @author takamflore
 */
@Stateless
public class NotificationDaoImpl implements NotificationDao{
    @PersistenceContext(unitName = "meteoCal_PU")
    private EntityManager em;
    @Inject
    private EventDao eventDao;
    @Inject
    private InvitationDao invit;
    List<Notification> notifications;
    Notification notification;
 
    
    @Override
    
    public void addNotication(Notification notify){
        em.persist(notify);
        
    }
    @Override
    public List<Notification> allNotification(){
        notifications= em.createNamedQuery("Notification.findAll").getResultList();
    return notifications;
    }
    
    @Override
    public List<Notification> allNotificationUser(int id){
        notifications= em.createNamedQuery("Notification.findAll").getResultList();
        for( Notification C:notifications){
            if(C.getUser().getId()!=id){
              try {
            notifications.remove(C);
        } catch (UnsupportedOperationException uoe) {
          //  notifications = new ArrayList<Notification>(notifications);
            notifications.remove(C);
        }
     }
        }
    return notifications;
    }
    
    @Override
    public Notification checkNotification(int iD){
         notification=em.find(Notification.class, iD);
    return notification;
    }
   @Schedule(hour="23")
    public void checkNotifcation(){
      
     DateTime today = new DateTime(); 
      DateTime yesterday = today.minusDays(1);
     java.util.Date  date= yesterday.toDate() ;//from dataTime to date
       List<Event> listEvent= eventDao.getAllEventOfDay(date);
       List<InvitationRequest> listInvit=invit.getAllInvitation();
       for(Event event:listEvent){
           listInvit.stream().filter((invit) -> ((event.getId().equals(invit.getEvent().getId())))).filter((invit) -> (invit.getAccepted())).map((_item) -> {
               notification= new Notification(event.getNameEvent(),event.getDescription());
             return _item;
         }).map((_item) -> {
             notification.setWeather(event.getWeather());
             return _item;
         }).map((_item) -> {
             em.persist(notification);
             return _item;
         }).forEach((_item) -> {
             new SendEmail().BSendMail(event);
         });
        }
    }

}
